package org.goldenport.g3.servlet

import scala.collection.mutable.ArrayBuffer
import javax.servlet._
import javax.servlet.http._
import org.goldenport.g3._
import G3Servlet._

/*
 * @since   Oct. 11, 2010
 * @version Oct. 15, 2010
 * @author  ASAMI, Tomoharu
 */
class G3AuthFilter extends Filter {
  def init(config: FilterConfig) {}
  def destroy() {}

  def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
    val req = request.asInstanceOf[HttpServletRequest]
    val res = response.asInstanceOf[HttpServletResponse]
    val target = req.getRequestURI
    val session = req.getSession
    val path = req.getPathInfo
    println("G3AuthFilter path = " + path)
    if (path == LoginUri || path == LogoutUri) {
        chain.doFilter(request, response)
    } else if (session == null) {
      val session2 = req.getSession(true)
      session2.setAttribute(SessionTarget, target)
      res.sendRedirect(loginUri(req))
    } else {
      val user = session.getAttribute(SessionUser)
      if (user == null) {
        session.setAttribute(SessionTarget, target)
        res.sendRedirect(loginUri(req))
      } else {
        chain.doFilter(request, response)
      }
    }
  }
}
